//
//  DisplayViewController.m
//  SmartSmartHome
//
//  Created by Yahaong on 16/8/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "DisplayViewController.h"
#import "HomeFlowLayout.h"
#import "SearchNetwayButton.h"
#define kTitleFont [UIFont systemFontOfSize:15]

//// 默认标题间距
//static CGFloat const margin = 20;
//static NSString *const reuseIdentifierID = @"ReuseIdentifier";
//
//CGFloat const kTitleScrollViewH = 48;
@interface DisplayViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>
/**标题高度*/
@property (nonatomic, assign) CGFloat titleHeight;
/** 整体内容View 包含标题好内容滚动视图 */
@property (nonatomic, strong) UIView *contentView;
/** 标题滚动视图 */
@property (nonatomic, strong) UIScrollView *titleScrollView;
/** 内容滚动视图 */
@property (nonatomic, strong) UICollectionView *contentScrollView;
/** 内容滚动视图 */
@property (nonatomic, strong) HomeFlowLayout *flowLayout;
/* 是否初始化 */
@property (nonatomic, assign) BOOL isInitial;
/** 下标视图 */
@property (nonatomic, weak) UIView *underLine;
/** 所以标题宽度数组 */
@property (nonatomic, strong) NSMutableArray *titleWidths;
/** 所以标题控件 */
@property (nonatomic, strong) NSMutableArray *titleLabels;
/** 标题间距 */
@property (nonatomic, assign) CGFloat titleMargin;
/** 记录是否点击 */
@property (nonatomic, assign) BOOL isClickTitle;
/** 计算上一次选中角标 */
@property (nonatomic, assign) NSInteger selIndex;
/** 记录是否在动画 */
@property (nonatomic, assign) BOOL isAniming;
/** 记录上一次内容滚动视图偏移量 */
@property (nonatomic, assign) CGFloat lastOffsetX;

@end

@implementation DisplayViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initial];
    }
    return self;
}
- (void)awakeFromNib
{
    [self initial];
}
- (void)initial
{
//    // 初始化标题高度
//    _titleHeight = kIphoneSize_Height( kTitleScrollViewH);
//    
//    self.automaticallyAdjustsScrollViewInsets = NO;
//    self.edgesForExtendedLayout = UIRectEdgeNone;
//    [self.view addSubview:self.contentView];
//    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view).offset(UIEdgeInsetsMake(0, 0, 5, 0));
//    }];
//    [self.contentView addSubview:self.titleScrollView];
//    self.titleScrollView.frame = CGRectMake(0, 0, kScreenWidth,_titleHeight);
//    [self.contentView insertSubview:self.contentScrollView belowSubview:self.titleScrollView];
//    [self.contentScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.titleScrollView.bottom);
//        make.leading.trailing.bottom.equalTo(self.contentView);
//    }];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    if (_isInitial == NO) {
//        _isInitial = YES;
//   //      注册cell
//        [self.contentScrollView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseIdentifierID];
//        if (self.childViewControllers.count == 0) return;
//        [self setUpTitleWidth];
//        [self setUpAllTitle];
//    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    SearchNetwayButton *searchBtn = [[SearchNetwayButton alloc]init];
    [searchBtn addTarget:self action:@selector(searchNetway) forControlEvents:UIControlEventTouchUpInside];
    [searchBtn setTitle:@"休息下" forState:UIControlStateNormal];
    
    [searchBtn setImage:[UIImage imageNamed:@"powerSocketClose"] forState:UIControlStateNormal];
    [self.view addSubview:searchBtn];
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(300);
        make.centerX.equalTo(self.view);
        make.top.equalTo(50);
        make.height.equalTo(220);
    }];
    return;
}


- (void)setUpTitleWidth
{
    NSInteger count = self.childViewControllers.count;
    NSArray *titles = [self.childViewControllers valueForKey:@"title"];
    CGFloat  totalWidth = 0;
    //计算宽度
    for (NSString *title in titles) {
        if ([title isKindOfClass:[NSNull class]]) {
            NSException *excp = [NSException exceptionWithName:@"ZTDisplayViewControllerException" reason:@"没有设置Controller.title属性，应该把子标题保存到对应子控制器中" userInfo:nil];
            [excp raise];
        }
        CGRect titleBounds = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleFont} context:nil];
        
        CGFloat width = titleBounds.size.width;
        [self.titleWidths addObject:@(width)];
        totalWidth += width;
    }
    if (totalWidth > kScreenWidth) {
        self.titleMargin = margin;
        self.titleScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, self.titleMargin);
        return;
    }
    CGFloat titleMargin = (kScreenWidth - totalWidth) / (count +1);
    self.titleMargin = titleMargin < margin? margin: titleMargin;
    self.titleScrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, self.titleMargin);
}

- (void)setUpAllTitle
{
    // 遍历所有的子控制器
    NSUInteger count = self.childViewControllers.count;
    // 添加所有的标题
    CGFloat labelW = 0;
    CGFloat labelH = self.titleHeight;
    CGFloat labelX = 0;
    CGFloat labelY = 0;
    for (NSInteger i = 0; i < count; i++) {
        UIViewController *vc = self.childViewControllers[i];
        UILabel *label = [[UILabel alloc] init];
        label.userInteractionEnabled = YES;
        label.tag = i;
        label.textColor = [UIColor blackColor];
        label.font = self.titleFont;
        label.text = vc.title;
        labelW = [self.titleWidths[i] floatValue];
        UILabel *lastLabel = [self.titleLabels lastObject];
        labelX = self.titleMargin + CGRectGetMaxX(lastLabel.frame);
        label.frame = CGRectMake(labelX, labelY, labelW, labelH);
        // 监听标题的点击
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(titleClick:)];
        [label addGestureRecognizer:tap];
        [self.titleLabels addObject:label];
        [self.titleScrollView addSubview:label];
        if (i == _selectIndex) {
            [self titleClick:tap];
        }
    }
    // 设置标题滚动视图的内容范围
    UILabel *lastLabel = self.titleLabels.lastObject;
    self.titleScrollView.contentSize = CGSizeMake(CGRectGetMaxX(lastLabel.frame), 0);
    self.titleScrollView.showsHorizontalScrollIndicator = NO;

}
- (void)titleClick:(UITapGestureRecognizer *)tapGres {
    // 记录是否点击标题
    self.isClickTitle = YES;
    // 获取对应标题label
    UILabel *label = (UILabel *)tapGres.view;
    NSInteger i = label.tag;
    [self selectLabel:label];
    CGFloat offsetX = i * kScreenWidth;
    self.contentScrollView.contentOffset = CGPointMake(offsetX, 0);
    self.lastOffsetX = offsetX;
    self.selIndex = i;
    // 点击事件处理完成
    self.isClickTitle = NO;
}
#pragma mark - UIScrollViewDelegate

// 减速完成
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat offsetX = scrollView.contentOffset.x;
    // 获取角标
    NSInteger i = offsetX / kScreenWidth;
    // 选中标题
    [self selectLabel:self.titleLabels[i]];
}
- (void)selectLabel:(UILabel *)label
{
    for (UILabel *labelView in self.titleLabels) {
        if (label == labelView) continue;
        labelView.textColor = [UIColor blackColor];
    }
    // 修改标题选中颜色
    label.textColor = RGBColor(239, 75, 58);
    // 设置标题居中
    [self setLabelTitleCenter:label];
    // 设置下标的位置
    [self setUpUnderLine:label];
}
// 让选中的按钮居中显示
- (void)setLabelTitleCenter:(UILabel *)label
{
    CGFloat offsetX = label.center.x - kScreenWidth * 0.5;
    if (offsetX < 0) {
        offsetX = 0;
    }
    CGFloat maxOffsetX = self.titleScrollView.contentSize.width - kScreenWidth + _titleMargin;
    if (maxOffsetX < 0) {
        maxOffsetX = 0;
    }
    if (offsetX > maxOffsetX) {
        offsetX = maxOffsetX;
    }
    // 滚动区域
    [self.titleScrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
}
// 设置下标的位置
- (void)setUpUnderLine:(UILabel *)label
{
    CGRect titleBounds = [label.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleFont} context:nil];
    CGFloat underLineH = 2;
    self.underLine.yh_y = label.yh_height - underLineH;
    self.underLine.yh_height = underLineH;
    // 最开始不需要动画
    if (self.underLine.yh_x == 0) {
        self.underLine.yh_width = titleBounds.size.width;
        self.underLine.yh_x = label.yh_x;
        return;
    }
    // 点击时候需要动画
    [UIView animateWithDuration:0.25 animations:^{
        self.underLine.yh_width = titleBounds.size.width;
        self.underLine.yh_x = label.yh_x;
    }];
}
// 监听滚动动画是否完成
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    self.isAniming = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 点击和动画的时候不需要设置
    if ( self.titleLabels.count == 0) return;
    // 获取偏移量
    CGFloat offsetX = scrollView.contentOffset.x;
    // 获取左边角标
    NSInteger leftIndex = offsetX / kScreenWidth;
    // 左边按钮
    UILabel *leftLabel = self.titleLabels[leftIndex];
    // 右边角标
    NSInteger rightIndex = leftIndex + 1;
    // 右边按钮
    UILabel *rightLabel = nil;
    if (rightIndex < self.titleLabels.count) {
        rightLabel = self.titleLabels[rightIndex];
    }
    // 设置下标偏移
    [self setUpUnderLineOffset:offsetX rightLabel:rightLabel leftLabel:leftLabel];
    // 记录上一次的偏移量
    _lastOffsetX = offsetX;
}
// 设置下标偏移
- (void)setUpUnderLineOffset:(CGFloat)offsetX rightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel
{
    if (_isClickTitle) return;
    // 获取两个标题中心点距离
    CGFloat centerDelta = rightLabel.yh_x - leftLabel.yh_x;
    // 标题宽度差值
    CGFloat widthDelta = [self widthDeltaWithRightLabel:rightLabel leftLabel:leftLabel];
    // 获取移动距离
    CGFloat offsetDelta = offsetX - _lastOffsetX;
    // 计算当前下划线偏移量
    CGFloat underLineTransformX = offsetDelta * centerDelta / kScreenWidth;
    // 宽度递增偏移量
    CGFloat underLineWidth = offsetDelta * widthDelta / kScreenWidth;
    self.underLine.yh_width += underLineWidth;
    self.underLine.yh_x += underLineTransformX;
}
// 获取两个标题按钮宽度差值
- (CGFloat)widthDeltaWithRightLabel:(UILabel *)rightLabel leftLabel:(UILabel *)leftLabel
{
    CGRect titleBoundsR = [rightLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleFont} context:nil];
    CGRect titleBoundsL = [leftLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.titleFont} context:nil];
    
    return titleBoundsR.size.width - titleBoundsL.size.width;
}
- (NSMutableArray *)titleLabels
{
    if (_titleLabels == nil) {
        _titleLabels = [NSMutableArray array];
    }
    return _titleLabels;
}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return 5;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifierID forIndexPath:indexPath];
    // 移除之前的子控件
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

    UIViewController *vc =   self.childViewControllers[indexPath.item];
    
    vc.view.frame = CGRectMake(0, 0, self.contentScrollView.yh_width, self.contentScrollView.yh_height);
    
    [cell.contentView addSubview:vc.view];
    
    return cell;
}
#pragma mark <lazy loading>

- (UIView *)underLine
{
    if (_underLine == nil) {
        UIView *underLineView = [[UIView alloc] init];

        underLineView.backgroundColor = RGBColor(239, 75, 58);
        
        [self.titleScrollView addSubview:underLineView];
        _underLine = underLineView;
    }
    return _underLine;
}

- (UIFont *)titleFont
{
    if (_titleFont == nil) {
        _titleFont = kTitleFont;
    }
    return _titleFont;
}

- (NSMutableArray *)titleWidths
{
    if (_titleWidths == nil) {
        _titleWidths = [NSMutableArray array];
    }
    return _titleWidths;
}
- (UIView *)contentView
{
    if (!_contentView) {
        _contentView = [[UIView alloc]init];
    }
    return _contentView;
}

- (UIScrollView *)titleScrollView
{
    if (!_titleScrollView ) {
        _titleScrollView = [[UIScrollView alloc]init];
        _titleScrollView.backgroundColor = [UIColor whiteColor];
    }
    return _titleScrollView;
}

- (HomeFlowLayout *)flowLayout
{
    if (!_flowLayout) {
        _flowLayout = [[HomeFlowLayout alloc]init];
    }
    return _flowLayout;
}
- (UICollectionView *)contentScrollView
{
    if (!_contentScrollView) {
        _contentScrollView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
        _contentScrollView.pagingEnabled = YES;
        _contentScrollView.showsHorizontalScrollIndicator = NO;
        _contentScrollView.bounces = NO;
        _contentScrollView.delegate = self;
        _contentScrollView.dataSource = self;
        
    }
    return _contentScrollView;
}

@end
